import {UGroup} from "../index";
import {ULine, UText} from "../components/index";
import Utils from "../utils/Utils";

const {ceil} = Utils

class GridLayer extends UGroup {

  gridOpt: Required<UComponent.GridOpt> = {
    font: {
      color: '#000000',
      fontSize: 14
    },
    line: {
      color: '#000000',
      spacing: 50
    }
  }

  constructor() {
    super({zIndex: -1, name: "grid_layer"});
    this.init()
  }

  /**
   * @description 开启网格线
   */
  init(): GridLayer {
    const [width, height] = [1500, 800]

    const {line: {color: lineColor, spacing}, font: {color: fontColor, fontSize}} = this.gridOpt
    const column = ceil(height / spacing)  // 列
    const row = ceil(width / spacing)    // 行

    for (let i = 0; i <= column; i++) {
      const line = new ULine({
        lineWidth: 1,
        pointList: [
          [0, i * spacing],
          [width, i * spacing]
        ],
        color: lineColor
      })

      const topText = new UText({
        content: `${i * spacing}`,
        textBaseline: 'middle',
        fontSize,
        color: fontColor,
        x: 0,
        y: i * spacing
      })
      const bottomText = new UText({
        content: `${i * spacing}`,
        fontSize,
        color: fontColor,
        x: width,
        y: i * spacing,
        textBaseline: 'middle',
        direction: 'rtl'
      })

      this.add(line, topText, bottomText)
    }

    for (let j = 0; j <= row; j++) {
      const line = new ULine({
        lineWidth: 1,
        pointList: [
          [j * spacing, 0],
          [j * spacing, height]
        ],
        color: lineColor
      })

      const leftText = new UText({
        content: `${j * spacing}`,
        textBaseline: 'hanging',
        textAlign: 'center',
        fontSize,
        color: fontColor,
        x: j * spacing,
        y: 0
      })
      const rightText = new UText({
        content: `${j * spacing}`,
        fontSize,
        color: fontColor,
        x: j * spacing,
        y: height,
        textBaseline: 'alphabetic',
        direction: 'rtl',
        textAlign: 'center',
      })

      this.add(line, leftText, rightText)
    }

    return this
  }
}

export default GridLayer
